package cz.none.bezbarier.web.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import cz.none.bezbarier.web.form.FiltreForm;
import cz.none.bezbarier.web.form.PlaceForm;
import cz.none.bezbarier.web.model.Place;
import cz.none.bezbarier.web.repository.PlaceRepository;
import cz.none.bezbarier.web.service.PlaceService;
import cz.none.bezbarier.web.service.UserService;
import cz.none.bezbarier.web.util.Constants;

@Service
public class PlaceServiceImpl extends BaseServiceImpl<PlaceForm, Place, String> implements PlaceService {

	@Autowired
	private PlaceRepository repository;

	@Autowired
	private UserService service;

	@Override
	public Page<Place> getPlaces(Integer pageNumber, FiltreForm form) {
		PageRequest pageRequest = new PageRequest(pageNumber - 1, Constants.Common.PAGE_SIZE);

		if (null != form.getType() && nnae(form.getName())) {
			return repository.findByTypeAndName(form.getType(), form.getName(), pageRequest);
		} else if (null != form.getType()) {
			return repository.findByType(form.getType(), pageRequest);
		} else if (nnae(form.getName())) {
			return repository.findByName(form.getName(), pageRequest);
		} else {
			return repository.findAll(pageRequest);
		}
	}

	private boolean nnae(String string) {
		if (null == string) {
			return false;
		}
		if ("".equals(string)) {
			return false;
		}

		return true;
	}

	@Override
	protected Place changeModel(PlaceForm form, Place model) {
		model.setAuthor(service.getCurrentUser());
		return model;
	}

	@Override
	protected JpaRepository<Place, String> getRepository() {
		return repository;
	}

	@Override
	public List<cz.none.bezbarier.web.webmodel.Place> getPlaces() {
		return cz.none.bezbarier.web.webmodel.Place.createPlaces(this.findAll());
	}

}
